package weaver.interfaces.holyview.duss.util;

import net.sf.json.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;


public class InvokeHelper {

    public static String POST_K3CloudURL = "http://8.136.106.175/k3cloud";
    private static String sessionkey = "kdservice-sessionid";
    private static String aspnetsessionkey = "ASP.NET_SessionId";
    private static String sessionValue = "";
    private static String aspnetsessionValue = "";
    public static Map map = new HashMap();

    static {
        map.put("Save", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc");
        map.put("View", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc");
        map.put("Query", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc");
        map.put("Submit", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit.common.kdsvc");
        map.put("Audit", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit.common.kdsvc");
        map.put("UnAudit", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.UnAudit.common.kdsvc");
        map.put("StatusConvert", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.StatusConvert.common.kdsvc");
        map.put("Draft", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Draft.common.kdsvc");
    }

    public static String getUser() {
        JSONObject userInfo = new JSONObject();
        userInfo.put("acctID", "5ff549f109f188");
        userInfo.put("username", "OA");
        userInfo.put("password", "Oa@Kingdee2022");
        userInfo.put("lcid", "2052");
        return userInfo.toString();
    }

    // 调用
    public static String Invoke(String deal, String formId, String content) {
        // 定义httpClient的实例
        HttpClient httpclient = new DefaultHttpClient();
        JSONObject jsonResult = null;
        String result = "";
        try {
            //登录，校验用户的API接口地址
            String Login_URL = POST_K3CloudURL + "/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc";
            HttpPost method = new HttpPost(new URI(Login_URL));
            StringEntity entity = new StringEntity(getUser(), "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            method.setEntity(entity);
            HttpResponse response = httpclient.execute(method);
            if (response.getStatusLine().getStatusCode() == 200) {
                String str = "";
                // 读取服务器返回过来的json字符串数据
                str = EntityUtils.toString(response.getEntity());
                // 把json字符串转换成json对象
                jsonResult = JSONObject.fromObject(str);
                //判断登录是否成功
                if (jsonResult.getInt("LoginResultType") == 1) {
                    System.out.println("登录成功！");
                    // 获取Cookie
                    Header[] headers = response.getHeaders("Set-Cookie");
                    for (int i = 1; i < headers.length; i++) {
                        Header header = headers[i];
                        String headerValue = header.getValue();
                        // 登录成功返回的登录session信息，保存下来，下面再调用接口的时候传给服务端
                        if (headerValue.trim().startsWith(sessionkey)) {
                            int endIndex = headerValue.indexOf(';');
                            sessionValue = headerValue.substring(20, endIndex);
                        } else if (headerValue.trim().startsWith(aspnetsessionkey)) {
                            int endIndex = headerValue.indexOf(';');
                            aspnetsessionValue = headerValue.substring(18, endIndex);
                        }
                    }


                } else {
                    System.out.println("登录失败！");
                }
            } else {
                System.out.println("登录异常！");
            }
            // 请求发送成功，并得到响应
        } catch (Exception e) {
            e.printStackTrace();
            return "post请求提交失败";
        }
        try {
            // 数据接口地址
            String url = POST_K3CloudURL + "/" + map.get(deal).toString();
            HttpPost method = new HttpPost(new URI(url));
            //保存参数
            JSONObject params = new JSONObject();
            if (!("Query").equals(deal)) {
                params.put("formid", formId);
            }
            params.put("data", content);
            StringEntity entity = new StringEntity(params.toString(), "UTF-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            //把成功登录的Session信息传进去，获取连接信息
            method.setHeader(sessionkey, sessionValue);
            method.setHeader(aspnetsessionkey, aspnetsessionValue);
            //方法参数
            method.setEntity(entity);
            HttpResponse response = httpclient.execute(method);
            // 请求发送成功，并得到响应
            if (response.getStatusLine().getStatusCode() == 200) {
                System.out.println("请求成功");
                // 读取服务器返回过来的json字符串数据
                result = EntityUtils.toString(response.getEntity());
            }
        } catch (Exception e) {
            System.out.println("post请求提交失败:" + e);
        }
        return result;
    }

    // Save
    public static String Save(String formId, String content) {
        return Invoke("Save", formId, content);
    }

    // View
    public static void View(String formId, String content) {
        Invoke("View", formId, content);
    }

    // Submit
    public static void Submit(String formId, String content) {
        Invoke("Submit", formId, content);
    }
    // Draft  暂存
    public static String Draft(String formId, String content) {
       return Invoke("Draft", formId, content);
    }

    // Audit
    public static void Audit(String formId, String content) {
        Invoke("Audit", formId, content);
    }

    // UnAudit
    public static void UnAudit(String formId, String content) {
        Invoke("UnAudit", formId, content);
    }

    // StatusConvert
    public static void StatusConvert(String formId, String content) {
        Invoke("StatusConvert", formId, content);
    }

    // StatusConvert
    public static String Query(String formId, String content) {
        return Invoke("Query", formId, content);
    }
}
